package com.scdt.china.shorturl.service;

import com.scdt.china.shorturl.common.Constants;
import com.scdt.china.shorturl.common.GlobalErrorCode;
import com.scdt.china.shorturl.common.ResultVo;
import com.scdt.china.shorturl.pojo.Url;
import com.scdt.china.shorturl.utils.JacksonUtil;
import com.scdt.china.shorturl.utils.ShortUrlUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.xml.transform.Result;
import java.time.LocalDateTime;

/**
 * @Author: zhouchao
 * @Date: 2021/12/02 23:32
 * @Description:
 */
@Slf4j
@Service
public class UrlService {

    /**
     *
     * @param shortUrl {@link String} 短码
     * @return ResultVo
     */
    public ResultVo<Url> getShortUrl(String shortUrl){
        Url url = Constants.URL_MAP.get(shortUrl);
        if (url == null) {
            log.debug("未查询到相关短链接：{}", shortUrl);
            return ResultVo.failure(GlobalErrorCode.NO_SHORT_URL, null);
        }
        log.debug("返回的长连接信息为：{}", JacksonUtil.toJson(url));
        return ResultVo.success(url);
    }

    public ResultVo<String> saveShortUrl(String longUrl,String host){
        String shortCode = ShortUrlUtils.shortUrl(longUrl);
        log.debug("生成的短链接码为：{}", shortCode);
        host += shortCode;

        Url url = new Url();
        url.setCreateTime(LocalDateTime.now());
        url.setLongUrl(longUrl);
        url.setShortUrl(host);

        Constants.URL_MAP.put(shortCode, url);
        return ResultVo.success(host);
    }

}
